local blockScale = 2
local FrameLoader = require("Utils.FrameLoader")

local Consts = require("Data.Consts")
local PrefabFactory = require("Utils.PrefabFactory")
local enhancement = require("Data.TableEnhancement")
G = {}
G.frameLoader = FrameLoader.new(1, 1) -- 分帧加载器
G.prefabFactory = PrefabFactory.new()
G.tickables = {G.frameLoader}

local xCount = 5
local yCount = 5
local zCount = 5

BASIC_OXYGEN = 100

local enhance1Level = {}
local oxygen = {}
local money = {}
local triggerTask1 = {}
local triggerEnhanceCount = {}
local UINodes = require("Data.UINodes")

-- 游戏开始事件
LuaAPI.global_register_trigger_event({EVENT.GAME_INIT}, function()
    LuaAPI.global_register_custom_event("强化1点击", function(name, unit, data)
        print("当前unit,执行了强化哦")
        print("=== 调试 data 结构 ===")

        -- 检查 data 是否为空或无效
        if not data then
            print("data 为空")
            return
        end
        print(data)
        -- 检测够钱不
        local roleId = data.role_id
        -- triggerEnhanceCount[roleId] = triggerEnhanceCount[roleId]+1
        -- if(triggerEnhanceCount[roleId]>=2) then

        -- end

        -- 基础钱+每级增加的钱*级别递增钱
        local price = enhancement.OxyGenAdd.Price + enhance1Level[roleId] * enhancement.OxyGenAdd.PriceAdd
        local role = GameAPI.get_role(roleId)
        if (money[roleId] < price) then
            role.show_tips("金钱不够")
            return
        end
        role.show_tips("强化成功")
        LuaAPI.global_send_custom_event("进行强化", nil)
        money[roleId] = money[roleId] - price
        role.set_attr_bonus_fixed(Consts.MoneyType.Gold, money[data.role_id])
        enhance1Level[roleId] = enhance1Level[roleId] + 1
        print("强化后等级:" .. enhance1Level[data.role_id])
    end)

    LuaAPI.global_register_trigger_event({EVENT.CUSTOM_EVENT, "打开商店"}, function(name, unit, data)
        print("方块触发销毁")
        print("=== 调试 data 结构 ===")

        -- 检查 data 是否为空或无效
        if not data then
            print("data 为空")
            return
        end

        role = GameAPI.get_role(data.role_id)
        role.set_attr_bonus_fixed(Consts.MoneyType.Gold, money[data.role_id])
    end)

    LuaAPI.global_register_custom_event("关闭强化弹窗", function(name, unit, data)
        print("当前unit,执行了强化哦")
        print("=== 调试 data 结构 ===")

        -- 检查 data 是否为空或无效
        if not data then
            print("data 为空")
            return
        end
        GameAPI.get_role(data.role_id).set_node_visible(UINodes["强化弹窗"], false)
    end)

    -- 遍历所有有效角色
    for _, role in ipairs(GameAPI.get_all_valid_roles()) do

        -- 隐藏商品操作按钮
        local roleId = role.get_roleid()
        money[roleId] = 0.0
        oxygen[roleId] = BASIC_OXYGEN
        enhance1Level[roleId] = 1
        triggerTask1[roleId] = false
        triggerEnhanceCount[roleId] = 0
        print("玩家氧气值:" .. oxygen[role.get_roleid()])
        role.set_label_text(UINodes["强化1描述"], enhancement.OxyGenAdd.Name)
        role.set_label_text(UINodes["强化1价格"], tostring(enhancement.OxyGenAdd.Price))

        local u = role.get_ctrl_unit()
        LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "强化1点击"}, function(name, actor, data)

            print("加氧气拉，找到实")

        end)

        LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "恢复氧气"}, function(name, actor, data)

            print("恢复氧气")
            local afterOxygen = oxygen[roleId] + 50
            local maxOxygen = BASIC_OXYGEN + enhance1Level[roleId] * 50
            if (afterOxygen >= maxOxygen) then
                afterOxygen = maxOxygen
            end
            oxygen[roleId] = afterOxygen

        end)

        LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "方块销毁"}, function(name, actor, data)

            money[roleId] = money[roleId] + 200.0

        end)

    end

    local triggerId = nil

    -- 定时器
    local function _timerFunc(eventName, actor, data)
        for _, role in ipairs(GameAPI.get_all_valid_roles()) do
            -- 隐藏商品操作按钮

            local roleId = role.get_roleid()
            local oriDepth = math.floor(role.get_ctrl_unit().get_position().y)
            local depth = math.abs(oriDepth)
            role.set_label_text(UINodes["深度文本"], tostring(depth))
            print("当前深度:" .. depth)
            if (oriDepth <= -1 and not triggerTask1[roleId]) then
                print("任务好了:" .. depth)
                triggerTask1[roleId] = true
                LuaAPI.global_send_custom_event("达到深度4", nil)
            end

            if (oxygen[roleId] <= 0) then
                -- 传送回地面
            else
                oxygen[role.get_roleid()] = oxygen[role.get_roleid()] - 1

                -- 更新角色金币UI显示
                oxygen[role.get_roleid()] = oxygen[role.get_roleid()] - 1
                role.set_progressbar_max(UINodes["氧气进度条"], BASIC_OXYGEN + enhance1Level[roleId] * 50)
                role.set_progressbar_current(UINodes["氧气进度条"], oxygen[role.get_roleid()])
            end
        end
    end
    -- 将_timerFunc注册到全局触发器中
    triggerId = LuaAPI.global_register_trigger_event({EVENT.REPEAT_TIMEOUT, 1.0}, _timerFunc)
end)

local blockSize = 2

for k = 1, yCount do
    for i = 1, xCount do -- 10/2=5个方块
        for j = 1, zCount do
            local x = (i - 1) * blockSize + 1 -- 1, 3, 5, 7, 9
            local y = (k - 1) * blockSize + 1 -- 1, 3, 5, 7, 9
            local z = (j - 1) * blockSize + 1 -- 1, 3, 5, 7, 9
            G.prefabFactory:createPrefabWithCb( -- 预设类型
            Consts.PrefabType.UNIT_OBSTACLE, -- 预设ID
            1073741871, -- 创建位置
            math.Vector3(x, -y, z), -- 创建旋转
            math.Quaternion(0, 0, 0), -- 创建缩放
            math.Vector3(2, 2, 2), -- 创建成功后的回调
            function(unit)

            end)

        end
    end
end

local region = LuaAPI.query_unit("强化商店触发区域")
LuaAPI.global_register_trigger_event({EVENT.ANY_LIFEENTITY_TRIGGER_SPACE, Enums.TriggerSpaceEventType.ENTER,
                                      region.get_id()}, function(name, actor, data)
    print("进入触发区域！")
    print(data)
    local roleId = data.role_id
    data.event_unit.get_role().set_attr_bonus_fixed(Consts.MoneyType.Gold, money[roleId])
    data.event_unit.get_role().set_node_visible(UINodes["强化弹窗"], true)
end)

function G.addTickable(obj)
    assert(obj.update)
    table.insert(G.tickables, obj)
end

-- 移除可更新对象的函数
function G.removeTickable(obj)
    for i, v in ipairs(G.tickables) do
        if v == obj then
            table.remove(G.tickables, i)
            break
        end
    end
end

-- 定义每帧更新前的处理函数
local function onPreTick(_)
    for _, v in ipairs(G.tickables) do
        v:update()
    end
end

-- 定义每帧更新后的处理函数（当前为空）
local function onPostTick()
end

-- 设置帧更新处理器
LuaAPI.set_tick_handler(onPreTick, onPostTick)

